<template>
    <!-- lc 2023年3月13日 10点06分 -->
    <!-- 角色管理 -->
  <div id="sysRole">
      <el-card class="box-card">
        <el-row>
            <el-col :span="8">
                <el-input
                placeholder="请输入角色名称"
                v-model="roleName"
                clearable>
                </el-input>
            </el-col>
            <el-col :span="2" :offset="1">
                <el-button style="color: #d7000f; border: 1px solid #d7000f" @click="getSysRoleByPage" plain>查询</el-button>
            </el-col>
            <el-col :span="12">
                 <el-button @click="addRole" style="background-color: #d7000f; color: #fff;margin-left:80%" >新增</el-button>
            </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:20px">
            <el-col :span="24">
                <el-table
                    :data="sysRoleData"
                    border
                    style="width:100%">
                    <el-table-column
                    fixed
                    prop="id"
                    label="序号"
                    >
                    </el-table-column>
                    <el-table-column
                    prop="roleName"
                    label="角色名称"
                    >
                    </el-table-column>
                    <el-table-column
                    prop="roleCreateTime"
                    label="创建时间"
                    >
                    </el-table-column>
                    <el-table-column
                    fixed="right"
                    label="操作"
                    width="235">
                    <template slot-scope="scope">
                        <el-button @click="handleUpdate(scope.row)" style="background-color: #534947; color: #fff" size="mini">编辑</el-button>
                        <el-button @click="permissions(scope.row)" style="background-color: #34262c; color: #fff" size="mini">权限</el-button>
                        <el-button @click="deleteRole(scope.row)" style="background-color: #d7000f; color: #fff" size="mini">删除</el-button>
                    </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row style="text-align: center;margin-top:10px">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
            </el-pagination>
        </el-row>
    </el-card>
    <!-- 数据新增功能 -->
    <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
        <el-form :model="sysRoleForm" ref="sysRoleForm" :rules="rules">
            <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="sysRoleForm.roleName" autocomplete="off" ></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRole('sysRoleForm')" style="background: #C90003;border-color:#C90003;">确 定</el-button>
        </div>
    </el-dialog>
     <!-- 数据修改功能 -->
    <el-dialog title="角色编辑" :visible.sync="dialogFormVisibleUpdate">
        <el-form :model="sysRoleFormEdit"  ref="sysRoleFormEdit" :rules="rules">
            <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="sysRoleFormEdit.roleName" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
            <el-button type="primary" @click="updateRole('sysRoleFormEdit')" style="background: #C90003;border-color:#C90003;">确 定</el-button>
        </div>
    </el-dialog>
    <!-- 数据授权功能 -->
    <el-dialog title="权限授权" :visible.sync="dialogFormPermissions" :close-on-click-modal="false" append-to-body style="height:100%;width:50%;margin-left:30%;overflow-y: hidden">
        <el-tree
            :data="data"
            show-checkbox
            default-expand-all
            node-key="id"
            :default-checked-keys="sysRoleFormEdit.aa"
            ref="tree"
            highlight-current
            check-strictly
            :props="defaultProps">
        </el-tree>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="getCheckedKey" style="background: #C90003;border-color:#C90003;">确 定</el-button>
            <el-button @click="dialogFormPermissions = false">关闭</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'sysRole',
  data () {
        return {
            // 存放模糊查输入框输入的值
            roleName:"",
            // 分页全查存放的数组
            sysRoleData: [], 
            //分页
            page:{
                pageSize:10, // 条数
                pageNum:1, // 页数
                total:0
            },
            // 输入框宽度
            formLabelWidth: '120px',
            // 分页当前选中页
            currentPage4: 1,
            // 新增时对象
            sysRoleForm:{ 
                roleName: ''
            },
            // 修改时对象
            sysRoleFormEdit:{ 
                id: '',
                roleName: '',
                rolePermissions:"",
                aa:[]
            },
            // 新增弹框true弹出
            dialogFormVisible: false,
            // 修改弹框true弹出
            dialogFormVisibleUpdate: false, 
            // 数据授权true弹出
            dialogFormPermissions: false,
            // 新增修改校验
            rules: {
                roleName: [
                    { required: true, message: '角色不能为空', trigger: 'blur' }
                ]
            },
            //存放查询遍历后的菜单
            data: [],
            // 存放树对象
            defaultProps: {
                children: 'childs',
                label: 'menuName'
            },
        }
    },
    // 初始化加载数据
    mounted(){
        // 分页全查
        this.getSysRoleByPage() 
        // 菜单查询
        this.getMenuTree()
    }, 
    methods:{
        //查询所有菜单
        getMenuTree(){
            this.$axios.get("/role/getMenuTree").then(res=>{
                console.log(res.data.obj);
                this.data=res.data.obj
            }).catch(error => {
                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
            })
        },
        //角色授权
        getCheckedKey(){
            var rolePermissions=this.$refs.tree.getCheckedKeys().join(",")+','+this.$refs.tree.getHalfCheckedKeys()
            this.sysRoleFormEdit.rolePermissions=rolePermissions
            this.$axios.put("/role/savePermissions",this.sysRoleFormEdit)
                .then(res=>{
                    if(res.data.code="200"){
                        this.message("恭喜你，添加权限成功！","success")
                        this.dialogFormPermissions = false
                        this.sysRoleFormEdit={
                            aa:[]
                        }
                        this.getSysRoleByPage();
                    }else{
                        this.message("对不起，添加权限失败！","warning")
                    }
                }).catch(error => {
                    this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                })
        },
        //删除角色
        deleteRole(row){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'btnFalses',
            type: 'warning'
            }//删除提示框
            ).then(() => {
                this.$axios.delete("/role/deleteRole?id=" + row.id)
            .then(res =>{
                if(res.data.code==='200'){
                    this.message("恭喜你，删除成功！","success")
                    this.getSysRoleByPage()
                }else{
                    this.message('删除失败','warning')
                }
            }).catch(error =>{
                    alert(error)
            })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // 修改角色
        updateRole(sysRoleFormEdit) {
            var formdata = new FormData();
            formdata.set("id",this.sysRoleFormEdit.id)
            formdata.set("roleName",this.sysRoleFormEdit.roleName)
            this.$refs[sysRoleFormEdit].validate((valid) => {
            if (valid) {
                this.$axios.put("/role/updateRole",formdata)
                .then(res=>{
                    if(res.data.code==='200'){
                    this.message("恭喜你，修改数据成功！","success")
                            this.dialogFormVisibleUpdate = false
                            this.sysRoleFormEdit={
                                id:'',
                                roleName:""
                            }
                            this.getSysRoleByPage();// 重新渲染数据列表
                    }else{
                            this.message("对不起，修改失败！","warning")
                        }
                    }).catch(error => {
                        this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                })
            } else {
                return false;
            }
            });
        },
        //角色授权
        permissions(row){
            this.dialogFormPermissions = true
            this.sysRoleFormEdit.id = row.id
            this.sysRoleFormEdit.roleName=row.roleName
            this.sysRoleFormEdit.rolePermissions=row.rolePermissions
            this.sysRoleFormEdit.aa=this.sysRoleFormEdit.rolePermissions.split(',') 
            this.getMenuTree()
        },
         //修改按钮回显值
        handleUpdate(row){
            this.dialogFormVisibleUpdate=true
            this.sysRoleFormEdit.id = row.id
            this.sysRoleFormEdit.roleName=row.roleName
        },
        // 新增按钮弹出弹框
        addRole(){
            this.dialogFormVisible = true
        },
        // 新增角色
        saveRole(sysRoleForm) {
            var formdata = new FormData();
            formdata.set("roleName",this.sysRoleForm.roleName)
            this.$refs[sysRoleForm].validate((valid) => {
            if (valid) {
                this.$axios.post("/role/saveRole", formdata).
                then(res => {
                    if(res.data.obj>0){
                        this.message("恭喜你，保存数据成功！","success")
                        this.dialogFormVisible = false
                        this.sysRoleForm ={
                            roleName:""
                        }
                        this.getSysRoleByPage()
                    }else{
                        this.message("对不起，保存失败！","warning")
                    }
                }).catch(() => {
                    this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                })
            } else {
                return false;
            }
            });
        },
       //角色分页查+模糊查（角色名称）
        getSysRoleByPage () {
            this.$axios.get('/role/roleList', {
                params: {
                    roleName: this.roleName,
                    pageSize: this.page.pageSize,
                    pageNum: this.page.pageNum
                }
            })
            .then((res) => {
                this.sysRoleData = res.data.obj.content
                this.page.total = res.data.obj.total
            })
        },
        // 分页
        handleSizeChange(ps) {
            this.page.pageSize=ps;
            this.getSysRoleByPage()
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(pn) {
            this.page.pageNum=pn;
            this.getSysRoleByPage()
        },
        //消息提示框
        message(message,type){
            this.$message({
                message:message,
                type: type
            });
        },
    }

}
</script>
<style>
    .btnFalses{
    background: #C90003 !important;
            color: #fff !important;
            ;border-color:#C90003 !important;
    }
</style>
<style scoped>
/**
* 附件上传样式
*/
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.box-card {
    height: 100%;
    width: 100%
}
</style>
